package cn.abdl.springsecurity.utiils;

import cn.abdl.springsecurity.entity.dto.SysUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

public class SecurityUtil {

    /**
     * 获取当前登录用户的信息
     * return Authentication 权鉴对象
     */
    public static Authentication currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            return authentication;
        }
        return null;
    }

    /**
     * 验证当前用户是否登录
     *
     * @return boolean 是否登录
     */
    public static boolean isAuthentication() {
        // if security session eq s-id is not null to index
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !(auth instanceof AnonymousAuthenticationToken);
    }

    /**
     * 获取当前登录用户对象
     * retrun SysUser
     */
    public static Object currentUserObj() {
        return SecurityUtil.currentUser().getPrincipal();
    }

    public static boolean userHasAuthority(String authority) {
        SysUser principal = (SysUser) currentUser().getPrincipal();
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) principal.getAuthorities();

        for (GrantedAuthority grantedAuthority : authorities) {
            if (authority.equals(grantedAuthority.getAuthority())) {
                return true;
            }
        }

        return false;
    }

}
